package com.sean.community.service;

import com.sean.community.dao.CommentMapper;
import com.sean.community.entity.Comment;
import com.sean.community.util.CommunityConstant;
import com.sean.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentService implements CommunityConstant {
    private CommentMapper commentMapper;
    private DiscussPostService discussPostService;
    private SensitiveFilter sensitiveFilter;

    @Autowired
    public void setCommentMapper(CommentMapper commentMapper) {
        this.commentMapper = commentMapper;
    }

    @Autowired
    public void setDiscussPostService(DiscussPostService discussPostService) {
        this.discussPostService = discussPostService;
    }

    @Autowired
    public void setSensitiveFilter(SensitiveFilter sensitiveFilter) {
        this.sensitiveFilter = sensitiveFilter;
    }

    public List<Comment> findCommentByEntity(int entityType, int entityId, int offset, int limit){
        return commentMapper.selectCommentsByEntity(entityType, entityId, offset, limit);
    }

    public int findCommentCount(int entityType, int entityId){
        return commentMapper.selectCountByEntity(entityType, entityId);
    }

    /**
     * 添加评论
     * @param comment 评论实体
     * @return 影响行数
     */
    // 事务隔离级别 RC 传播级别 REQUIRED
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if(comment == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        // 内容过滤，xss
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        // 敏感词过滤
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        // 添加评论
        int rows = commentMapper.insertComment(comment);
        // 更新帖子的评论数量
        if(comment.getEntityType() == ENTITY_TYPE_DISCUSS_POST){
            // 查询当前帖子的评论数量
            int currentCommentCount = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
            // 更新帖子表的总评论数量
            discussPostService.updateCommentCount(comment.getEntityId(), currentCommentCount);
        }
        return rows;
    }

    public Comment findCommentById(int id){
        return commentMapper.selectCommentById(id);
    }

    public List<Comment> findDiscussPostCommentByUser(int userId, int offset, int limit){
        return commentMapper.selectDiscussPostCommentByUser(userId, offset, limit);
    }

    public int findDiscussPostCommentCountByUser(int userId){
        return commentMapper.selectDiscussPostCommentCountByUser(userId);
    }
}
